<template>
<!-- 慢病政策管理 -->
  <div class="policy-container">
    <!-- 搜索栏 -->
    <div class="search-container">
      <el-form :model="searchForm" class="search-form" label-width="80px">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="疾病名称">
              <el-input
                v-model="searchForm.diseaseName"
                placeholder="请输入疾病名称"
                clearable
              />
            </el-form-item>
          </el-col>
          
          <!-- <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="适用年度">
              <el-input
                v-model.number="searchForm.year"
                placeholder="请输入政策适用年度"
                clearable
              />
            </el-form-item>
          </el-col>
          
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="年度报销封顶线">
              <el-input
                v-model.number="searchForm.capAmount"
                placeholder="请输入报销封顶线（元）"
                clearable
              />
            </el-form-item>
          </el-col>
          
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="报销比例">
              <el-input
                v-model.number="searchForm.reimbursementRate"
                placeholder="请输入报销比例（0-1）"
                clearable
              />
            </el-form-item>
          </el-col>
          
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="政策名称">
              <el-input
                v-model="searchForm.policyName"
                placeholder="请输入政策名称"
                clearable
              />
            </el-form-item>
          </el-col>
          
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="疾病编码">
              <el-input
                v-model="searchForm.diseaseCode"
                placeholder="请输入疾病编码"
                clearable
              />
            </el-form-item>
          </el-col> -->
          
          <el-col :xs="24" :sm="24" :md="24" :lg="6" class="search-buttons">
            <el-button type="primary" @click="handleSearch">
              <i class="el-icon-search"></i> 搜索
            </el-button>
            <el-button @click="resetSearch">
              <i class="el-icon-refresh"></i> 重置
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="operation-buttons">
      <el-button type="primary" @click="handleAdd">
        <i class="el-icon-plus"></i> 新增政策
      </el-button>
    </div>

    <!-- 表格 -->
    <div class="table-container">
      <el-table
        :data="tableData"
        border
        stripe
        style="width: 100%"
        v-loading="loading"
        element-loading-text="数据加载中..."
        :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: 'bold' }"
      >
        <el-table-column prop="policyId" label="政策ID" width="100" align="center" />
        
        <el-table-column prop="year" label="适用年度" width="100" align="center" />
        
        <el-table-column prop="diseaseName" label="疾病名称" width="180" align="center">
          <template #default="{ row }">
            <span class="ellipsis" :title="row.diseaseName">{{ row.diseaseName }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="diseaseCode" label="疾病编码" width="120" align="center" />
        
        <el-table-column prop="policyName" label="政策名称" width="180" align="center">
          <template #default="{ row }">
            <span class="ellipsis" :title="row.policyName">{{ row.policyName }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="capAmount" label="年度报销封顶线(元)" width="160" align="center">
          <template #default="{ row }">
            {{ row.capAmount ? row.capAmount.toLocaleString() : '0' }}
          </template>
        </el-table-column>
        
        <el-table-column prop="reimbursementRate" label="报销比例" width="120" align="center">
          <template #default="{ row }">
            {{ (row.reimbursementRate || 0).toFixed(2) * 100 }}%
          </template>
        </el-table-column>
        
        <el-table-column prop="effectiveDate" label="生效日期" width="180" align="center">
          <template #default="{ row }">
            {{ formatDate(row.effectiveDate) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="expiryDate" label="失效日期" width="180" align="center">
          <template #default="{ row }">
            {{ formatDate(row.expiryDate) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template #default="{ row }">
            <el-tag 
              :type="row.status === 1 ? 'success' : 'danger'" 
              :effect="row.status === 1 ? 'light' : 'dark'"
              size="small"
            >
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="createTime" label="创建时间" width="180" align="center">
          <template #default="{ row }">
            {{ formatDate(row.createTime, 'YYYY-MM-DD HH:mm:ss') }}
          </template>
        </el-table-column>
        
        <el-table-column prop="updateTime" label="更新时间" width="180" align="center">
          <template #default="{ row }">
            {{ formatDate(row.updateTime, 'YYYY-MM-DD HH:mm:ss') }}
          </template>
        </el-table-column>
        
        <el-table-column prop="description" label="政策描述" width="200" align="center">
          <template #default="{ row }">
            <span class="ellipsis" :title="row.description || '-'" v-if="row.description">{{ row.description }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="{ row }">
            <el-button size="mini" type="primary" plain @click="handleEdit(row)">
              <i class="el-icon-edit"></i> 编辑
            </el-button>
            <el-button size="mini" type="danger" plain @click="handleDelete(row)">
              <i class="el-icon-delete"></i> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog 
      :title="dialogTitle" 
      v-model="dialogVisible" 
      width="700px" 
      :close-on-click-modal="false"
      :before-close="resetForm"
    >
      <el-form :model="formData" :rules="formRules" ref="formRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="适用年度" prop="year">
              <el-input 
                type="number" 
                v-model.number="formData.year" 
                placeholder="请输入适用年度"
                clearable
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="疾病名称" prop="diseaseName">
              <el-input 
                v-model="formData.diseaseName" 
                placeholder="请输入疾病名称"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="疾病编码" prop="diseaseCode">
              <el-input 
                v-model="formData.diseaseCode" 
                placeholder="请输入疾病编码"
                clearable
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="政策名称" prop="policyName">
              <el-input 
                v-model="formData.policyName" 
                placeholder="请输入政策名称"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="年度报销封顶线" prop="capAmount">
              <el-input 
                type="number" 
                v-model.number="formData.capAmount" 
                placeholder="请输入年度报销封顶线（元）"
                clearable
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="报销比例" prop="reimbursementRate">
              <el-input 
                type="number" 
                step="0.01" 
                v-model.number="formData.reimbursementRate" 
                placeholder="请输入报销比例（0-1）"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="生效日期" prop="effectiveDate">
              <el-date-picker
                v-model="formData.effectiveDate"
                type="date"
                placeholder="请选择生效日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                :disabled-date="date => date > new Date()"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="失效日期" prop="expiryDate">
              <el-date-picker
                v-model="formData.expiryDate"
                type="date"
                placeholder="请选择失效日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                :disabled-date="date => date < new Date(formData.effectiveDate) || date > new Date()"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="政策描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入政策描述"
          />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">
            <i class="el-icon-close"></i> 取消
          </el-button>
          <el-button type="primary" @click="submitForm">
            <i class="el-icon-check"></i> 确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request';
import { formatDate } from '@/utils/date';

export default {
  name: 'ChronicDiseasePolicyManagement',
  data() {
    return {
      // 搜索表单
      searchForm: {
        diseaseName: '',
        year: null,
        capAmount: null,
        reimbursementRate: null,
        policyName: '',
        diseaseCode: ''
      },
      
      // 表格数据
      tableData: [],
      loading: false,
      
      // 分页配置
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      
      // 对话框配置
      dialogVisible: false,
      dialogTitle: '新增政策',
      formData: {
        policyId: null,
        year: null,
        diseaseName: '',
        diseaseCode: '',
        policyName: '',
        capAmount: null,
        reimbursementRate: null,
        effectiveDate: null,
        expiryDate: null,
        description: '',
        status: 1
      },
      
      // 表单验证规则
      formRules: {
        year: [
          { required: true, message: '请输入适用年度', trigger: 'blur' },
          { type: 'number', message: '请输入数字', trigger: 'blur' }
        ],
        diseaseName: [
          { required: true, message: '请输入疾病名称', trigger: 'blur' },
          { min: 2, message: '疾病名称至少2个字符', trigger: 'blur' }
        ],
        diseaseCode: [
          { required: true, message: '请输入疾病编码', trigger: 'blur' },
          { pattern: /^[A-Za-z0-9]+$/, message: '疾病编码只能包含字母和数字', trigger: 'blur' }
        ],
        policyName: [
          { required: true, message: '请输入政策名称', trigger: 'blur' },
          { min: 2, message: '政策名称至少2个字符', trigger: 'blur' }
        ],
        capAmount: [
          { required: true, message: '请输入年度报销封顶线', trigger: 'blur' },
          { type: 'number', message: '请输入数字', trigger: 'blur' },
          { validator: (rule, value, callback) => {
              if (value && value <= 0) {
                callback(new Error('报销封顶线必须大于0'));
              } else {
                callback();
              }
            }, trigger: 'blur' }
        ],
        reimbursementRate: [
          { required: true, message: '请输入报销比例', trigger: 'blur' },
          { type: 'number', message: '请输入数字', trigger: 'blur' },
          { validator: this.validateRate, trigger: 'blur' }
        ],
        effectiveDate: [
          { required: true, message: '请选择生效日期', trigger: 'change' }
        ],
        expiryDate: [
          { required: true, message: '请选择失效日期', trigger: 'change' },
          { validator: (rule, value, callback) => {
              if (value && this.formData.effectiveDate && new Date(value) <= new Date(this.formData.effectiveDate)) {
                callback(new Error('失效日期必须晚于生效日期'));
              } else {
                callback();
              }
            }, trigger: 'change' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      }
    };
  },
  
  methods: {
    // 格式化日期
    formatDate(date, format = 'YYYY-MM-DD') {
      return formatDate(date, format);
    },
    
    // 验证报销比例
    validateRate(rule, value, callback) {
      if (value === undefined || value === null) {
        callback(new Error('请输入报销比例'));
      } else if (value < 0 || value > 1) {
        callback(new Error('报销比例必须在 0 到 1 之间'));
      } else {
        callback();
      }
    },
    
    // 获取数据列表
    fetchData() {
      this.loading = true;
      request.get('/chronicDiseasePolicy/list', {
        params: {
          current: this.pagination.currentPage,
          size: this.pagination.pageSize,
          ...this.searchForm
        }
      })
        .then(res => {
          if (res.code === 200) {
            this.tableData = res.data.records;
            this.pagination.total = res.data.total;
          } else {
            this.$message.error(res.message || '获取政策列表失败');
          }
        })
        .catch(err => {
          console.error('获取政策列表失败:', err);
          this.$message.error('加载政策列表失败');
        })
        .finally(() => {
          this.loading = false;
        });
    },
    
    // 搜索处理
    handleSearch() {
      this.pagination.currentPage = 1;
      this.fetchData();
    },
    
    // 重置搜索
    resetSearch() {
      this.searchForm = {
        diseaseName: '',
        year: null,
        capAmount: null,
        reimbursementRate: null,
        policyName: '',
        diseaseCode: ''
      };
      this.handleSearch();
    },
    
    // 分页大小变更
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.fetchData();
    },
    
    // 当前页变更
    handleCurrentChange(val) {
      this.pagination.currentPage = val;
      this.fetchData();
    },
    
    // 新增政策
    handleAdd() {
      this.dialogTitle = '新增政策';
      this.resetForm();
      this.dialogVisible = true;
      
      // 设置默认值
      const today = new Date();
      this.formData.status = 1; // 默认启用
      this.formData.effectiveDate = formatDate(today, 'YYYY-MM-DD'); // 默认今天
      this.formData.expiryDate = formatDate(
        new Date(today.setFullYear(today.getFullYear() + 1)), 
        'YYYY-MM-DD'
      ); // 默认一年后
    },
    
    // 编辑政策
    handleEdit(row) {
      this.dialogTitle = '编辑政策';
      this.formData = {
        ...row,
        effectiveDate: row.effectiveDate ? formatDate(row.effectiveDate, 'YYYY-MM-DD') : '',
        expiryDate: row.expiryDate ? formatDate(row.expiryDate, 'YYYY-MM-DD') : ''
      };
      this.dialogVisible = true;
    },
    
    // 删除政策
    handleDelete(row) {
      this.$confirm(`确认删除政策「${row.policyName}」吗？该操作不可恢复`, '提示', {
        type: 'warning',
        confirmButtonText: '确认删除',
        cancelButtonText: '取消'
      })
        .then(() => {
          request.post(`/chronicDiseasePolicy/delete/${row.policyId}`)
            .then(res => {
              if (res.code === 200) {
                this.$message.success('政策删除成功');
                this.fetchData();
              } else {
                this.$message.error(res.message || '政策删除失败');
              }
            })
            .catch(err => {
              this.$message.error('删除失败，请联系管理员');
              console.error('删除接口异常:', err);
            });
        })
        .catch(() => {});
    },
    
    // 提交表单
    submitForm() {
      this.$refs.formRef.validate(valid => {
        if (!valid) return;
        
        // 校验生效日期和失效日期
        if (this.formData.effectiveDate && this.formData.expiryDate) {
          if (new Date(this.formData.effectiveDate) >= new Date(this.formData.expiryDate)) {
            this.$message.error('失效日期必须晚于生效日期');
            return;
          }
        }

        const isEdit = !!this.formData.policyId;
        const apiUrl = isEdit ? '/chronicDiseasePolicy/update' : '/chronicDiseasePolicy/create';
        
        // 处理 BigDecimal 类型字段（前端传输字符串避免精度丢失）
        const params = {
          ...this.formData,
          capAmount: this.formData.capAmount?.toString(),
          reimbursementRate: this.formData.reimbursementRate?.toString()
        };

        request.post(apiUrl, params)
          .then(res => {
            if (res.code === 200) {
              this.$message.success(`${this.dialogTitle}成功`);
              this.dialogVisible = false;
              this.fetchData();
            } else {
              this.$message.error(`${this.dialogTitle}失败: ${res.message}`);
            }
          })
          .catch(err => {
            console.error(`${this.dialogTitle}接口异常:`, err);
            this.$message.error(`${this.dialogTitle}失败，请检查参数或联系管理员`);
          });
      });
    },
    
    // 重置表单
    resetForm() {
      this.$refs.formRef?.resetFields();
      this.formData = {
        policyId: null,
        year: null,
        diseaseName: '',
        diseaseCode: '',
        policyName: '',
        capAmount: null,
        reimbursementRate: null,
        effectiveDate: null,
        expiryDate: null,
        description: '',
        status: 1
      };
    }
  },
  
  created() {
    this.fetchData();
  }
};
</script>

<style scoped>
/* 基础容器样式 */
.policy-container {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

/* 搜索栏样式 */
.search-container {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f9fafc;
  border-radius: 6px;
  border: 1px solid #ebeef5;
}

/* 操作按钮样式 */
.operation-buttons {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

/* 表格样式 */
.table-container {
  overflow-x: auto;
}

.el-table {
  font-size: 14px;
  margin-top: 10px;
}

.el-table th {
  background-color: #f5f7fa;
  font-weight: 500;
  color: #333;
  text-align: center;
}

.el-table .cell {
  padding: 10px 8px;
  text-align: center;
}

/* 省略号样式 */
.ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  display: block;
}

/* 状态标签样式 */
.el-tag.success {
  background-color: rgba(103, 194, 58, 0.1);
  color: #67c23a;
  border-color: rgba(103, 194, 58, 0.2);
}

.el-tag.danger {
  background-color: rgba(245, 108, 108, 0.1);
  color: #f56c6c;
  border-color: rgba(245, 108, 108, 0.2);
}

/* 对话框底部样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 15px 20px;
  border-top: 1px solid #ebeef5;
  background-color: #f9fafc;
  border-radius: 0 0 6px 6px;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .el-table-column:not([fixed]) {
    min-width: 120px;
  }
}
</style>    